<?php

function reequipment_userapi_groupshippingcost($args)
{
    extract($args);

    /* Fields in table.
		shipping_id
		invoice_number
		cost
		company_id
   */

    // Optional arguments
    if (!isset($startnum)) {$startnum = 1;}
    if (!isset($numitems)) {$numitems = -1;}

    $dbconn =& xarDBGetConn();
    $xartable =& xarDBGetTables();
    $table = $xartable['reshipping'];

    $query = "SELECT company_id,
    				 MIN(cost) as min_cost,
    				 MAX(cost) as max_cost,
    				 AVG(cost) as avg_cost,
    				 SUM(cost) as sum_cost,
    				 COUNT(invoice_number) as count_invoices"
    		. " FROM $table";     		

    $where = array();
    $bind = array();
    
    if (!empty($company_id)) {
        $where[] = 'company_id = ?';
        $bind[] = (int)$company_id;
    }
    
    if (!empty($where)) {
        $query .= ' WHERE ' . implode(' AND ', $where);
    }

    $result =& $dbconn->SelectLimit($query, $numitems, $startnum-1, $bind);
    if (!$result) return;

    $tags = array();
    for (; !$result->EOF; $result->MoveNext()) {
        list($company_id, $min_cost, $max_cost, $avg_cost, $sum_cost, $count_invoices) = $result->fields;

        $tags[] = array(
        		'company_id'	=> $company_id,
        		'min_cost'		=> round($min_cost, 2),
                'max_cost' 		=> round($max_cost, 2),
                'avg_cost'		=> round($avg_cost, 2),
                'sum_cost'		=> round($sum_cost, 2),
                'count_invoices'=> $count_invoices
        );
    }

    $result->Close();
    return $tags;
}
?>